﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Thirteen23.TED.Data;
using Thirteen23.TED.Models;
using Thirteen23.TED.Views;

namespace Thirteen23.TED.Selectors
{
    public class TedTalksDataTemplateSelector : DataTemplateSelector
    {
        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            FrameworkElement element = ApplicationModel.Instance.MainPage.NavigationFrame.Content as FrameworkElement;

            if (element != null)
            {
                if (item is TedTalk)
                {
                    return element.FindResource("TedTalk") as DataTemplate;
                }
                else if (item is DateTile)
                {
                    return element.FindResource("DateTile") as DataTemplate;
                }
            }

            return null;
        }
    }

    public static class FrameworkElementExtensions
    {
        public static object FindResource(this FrameworkElement element, object resourceKey)
        {
            var currentElement = element;

            while (currentElement != null)
            {
                if (currentElement.Resources.ContainsKey(resourceKey))
                {
                    var resource = currentElement.Resources[resourceKey];
                    if (resource != null)
                    {
                        return resource;
                    }
                }
                foreach (var mergedDictionary in currentElement.Resources.MergedDictionaries)
                {
                    if (mergedDictionary.ContainsKey(resourceKey))
                    {
                        var resource = mergedDictionary[resourceKey];
                        if (resource != null)
                        {
                            return resource;
                        }
                    }
                }

                currentElement = currentElement.Parent as FrameworkElement;
            }

            return Application.Current.Resources[resourceKey];
        }
    }
}

